package cn.gxa.edu_adm.servlet;

import cn.gxa.edu_adm.bean.Student;
import cn.gxa.edu_adm.commn.model.ResultData;
import cn.gxa.edu_adm.service.impl.StudentServiceImpl;
import cn.gxa.edu_adm.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UploadStudentExcelServlet",urlPatterns = "/uploadStudentExcel")
@MultipartConfig
public class UploadStudentExcelServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得前端上传的文件
        Part part=request.getPart("studentExcel");
        ResultData   resultData=null;
        //记录每一行的数据  把每一个 换算成Student 对象 然后存入集合中
        List<Student> temp = new ArrayList();
        //根据指定的文件输入流导入Excel从而产生Workbook对象
        Workbook wb0 = new HSSFWorkbook(part.getInputStream());
        //获取Excel文档中的第一个表单
        Sheet sht0 = wb0.getSheetAt(0);
        try {
        //对Sheet中的每一行进行迭代
        for (Row r : sht0) {
            //如果当前行的行号（从0开始）未达到2（第三行）则从新循环
            if(r.getRowNum()<1){
                continue;
            }
            //创建实体类
            Student info=new Student();

                //取出当前行第1个单元格数据，并封装在info实体stuName属性上
                info.setStuName(r.getCell(1).getStringCellValue());
                info.setStuBirthday(StringUtils.formatDate(r.getCell(2).getStringCellValue()));
                info.setStuPhone(r.getCell(3).getStringCellValue());
                info.setStuIdCard(r.getCell(4).getStringCellValue());
                info.setStuSex(r.getCell(5).getStringCellValue().equals("男") ? 0 : 1);
                temp.add(info);

        }
            //把集合中的数据 插入数据库
            resultData= new StudentServiceImpl().batchAddStudent(temp);
        }catch (Exception  e){
            resultData=ResultData.error().message("数据格式有误,批量添加失败");
        }
        //响应给前端
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(resultData));
        writer.close();
    }

}
